package com.wits100.demoplayer;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.util.Map;

import fi.iki.elonen.NanoHTTPD;

/**
 * Created by terry on 2017-07-31.
 */

public class HttpServer extends NanoHTTPD {

    public final String TAG = "httpapi";

    private Context context;
    private Handler handler;

    public HttpServer(Handler handler, int port) {
        super(port);

        //this.context = context;
        this.handler = handler;
    }

    @Override
    public Response serve(IHTTPSession session) {
        Method method = session.getMethod();
        String uri = session.getUri();
        Log.i(TAG, method + " '" + uri + "' ");

        if (uri.equals("/report")) {
            Map<String, String> parms = session.getParms();
            String type = parms.get("type");
            String desc = parms.get("desc");

            String alarm = "Alarm: " + type;
            //Toast.makeText(context, alarm, Toast.LENGTH_LONG);
            Message msg = new Message();
            msg.what = Integer.parseInt(type);
            msg.getData().putString("desc", desc);
            msg.getData().putString("desc", type);
            handler.sendMessage(msg);
            Log.i(TAG, alarm);

            String resp = "{\"code\": 0}";
            return newFixedLengthResponse(resp);
        } else {

            String msg = "<html><body><h1>Hello server</h1>\n";
            Map<String, String> parms = session.getParms();
            if (parms.get("username") == null) {
                msg += "<form action='?' method='get'>\n" + "  <p>Your name: <input type='text' name='username'></p>\n" + "</form>\n";
            } else {
                msg += "<p>Hello, " + parms.get("username") + "!</p>";
            }

            msg += "</body></html>\n";

            return newFixedLengthResponse(msg);
        }
    }
}
